<template>
    <el-row v-loading="loading">
        <el-form v-if="type" ref="defailForm" :model="form" label-width="80px" :rules="rules">
            <el-form-item prop="title" label="标题">
                <el-input v-model="form.title" maxlength="100"></el-input>
            </el-form-item>
            <el-form-item prop="cover_url" ref="cover_url" label="封面">
                <el-input v-model="form.cover_url" type="hidden"></el-input>
                <div class="uploadcol">
                    <div class="uploadborder">
                        <img v-if="form.cover_url" :src="form.cover_url" />
                        <img v-else src="@/assets/img/uploadimg.jpg" />
                    </div>
                    <el-button type="primary" @click="isShowPic = true">请选择封面图片</el-button>
                </div>
                <select-img :show="isShowPic" @update="cleanDiaglog" :selectType="imgnum" @selectSure="selectImgs"
                    :source="1" :type="0"></select-img>
            </el-form-item>
            <el-form-item prop="level" label="级别" v-if="type === 'book'">
                <el-input v-model="form.level" maxlength="255"></el-input>
            </el-form-item>
            <el-form-item prop="content" label="内容">
                <component :is="getCompoentName()" :content="content || []" :id="id" @onFinish="handleFinish"
                    @handleDelContent="handleDelContent" :key="$route.fullPath">
                </component>
            </el-form-item>
            <el-form-item prop="remark" label="备注">
                <el-input type="textarea" v-model="form.remark" maxlength="255"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleCancel">返回</el-button>
                <el-button type="primary" @click="onSubmit()">{{ btnTxt }}</el-button>
                <el-button type="primary" @click="onSubmit(1)">发布到素材库并保存</el-button>
            </el-form-item>
        </el-form>
        <el-empty v-else description="请求参数有误!"></el-empty>
    </el-row>
</template>


<script>
import { mapState, mapActions } from 'vuex';

import BookContent from './components/BookContent.vue';
import VideoContent from './components/VideoContent.vue';
import PPTContent from './components/PPTContent.vue';
import AudioContent from './components/AudioContent.vue';
import {
    COURSEWARE_NUM_MAP,
} from "@/constant/kanke/courseware.js";


export default {
    name: "KanKeTextbookCourseWareBookDetail",
    components: {
        BookContent,
        VideoContent,
        PPTContent,
        AudioContent
    },
    data() {
        return {
            imgnum: 1,
            isShowPic: false,
            unit: '',
            form: {
                title: '',
                cover_url: '',
                content: '',
                level: '',
                remark: '',
            },
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'change' },
                    { min: 1, max: 100, message: '长度在 1 到 50 个字', trigger: 'change' }
                ],
                cover_url: [
                    { required: true, message: '请输入封面', trigger: 'change' },
                ]
            }
        }
    },
    computed: {
        ...mapState("courseware", ["detail", "content", 'loading']),
        type() {
            return this.$route.query?.type || ''
        },
        handleType() {
            return this.$route.query?.handleType || ''
        },
        unit_id() {
            return this.$route.query?.unit_id || ''
        },
        id() {
            return this.$route.query.id || ''
        },
        btnTxt() {
            const txtMap = {
                'book': '课本',
                'audio': '音频课件',
                'ppt': 'PPT课件',
                'video': '视频课件'
            }
            return `保存到${txtMap[this.type]}`
        }

    },
    watch: {
        detail: {
            handler(newVal) {
                if (newVal) {
                    this.form = { ...newVal }
                }
            },
            immediate: true
        },
        id: {
            handler(val) {
                if (val) {
                    this.$store.commit('courseware/setContentDetail', {})
                    this.$store.commit('courseware/setContent', [])
                    this.$store.commit('courseware/setDetail', {})
                    this.getDetail({ id: val });
                    this.getContent({ id: val });
                }
            },
            immediate: true

        }
    },
    methods: {
        ...mapActions("courseware", ["createBook", 'getDetail', 'getContent', 'updateBook', 'deleteContent']),
        handleDelContent(id) {
            this.deleteContent({ id }).then(res => {
                if (res.code == 200) {
                    this.$message.success(res.msg);
                    this.getContent({ id: this.id });
                }
            })
        },
        handleCancel() {
            this.$store.commit('courseware/setContentDetail', {})
            this.$store.commit('courseware/setContent', [])
            this.$store.commit('courseware/setDetail', {})
            this.$store.commit('courseware/setTableData', [])
            let source = this.type
            if (this.$route.query.source) {
                source = this.$route.query.source
            }
            // 生成一个时间戳变量
            const timestamp = new Date().getTime();
            this.$router.push({ name: 'Courseware', params: { type: source, timestamp } })
        },
        getCompoentName() {
            const typeMap = {
                'video': 'VideoContent',
                'book': 'BookContent',
                'audio': 'AudioContent',
                'ppt': 'PPTContent'
            }
            return typeMap[this.type]
        },
        onSubmit(publish_type = 0) {
            this.$refs['defailForm'].validate((valid) => {
                if (!valid) return false

                const unit_id = this.unit_id

                const params = { publish_type, book_type: COURSEWARE_NUM_MAP[this.type], unit_id, ...this.form }
                const api = this.id ? this.updateBook : this.createBook
                api(params).then(res => {
                    if (res.code == 200) {
                        this.$message.success(res.msg);
                        if (!this.id) {
                            const query = {
                                ...this.$route.query,
                                'handleType': 'edit',
                                id: res.data
                            }
                            this.$router.push({
                                name: "Bookdetail",
                                query
                            });
                        }
                    }
                })
            })
        },
        cleanDiaglog() {
            this.isShowPic = false;
        },
        selectImgs(res) {
            this.$set(this.form, 'cover_url', res[0].urls)
            this.isShowPic = false;
        },
        handleMakePage() {
            this.$router.push({ name: 'Makepage' })
        },
        handleFinish() {
            this.getContent({ id: this.id });
        }
    }
}


</script>
<style lang="scss" scoped>
.uploadcol {
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .uploadborder {
        img {
            width: 80px;
            height: 80px;
            margin-right: 40px;
        }

    }
}
</style>